<template>
    <div class="wrapper customer-box"  @click="cateShow = !cateShow">
        <el-form label-position="top" :inline="true" :model="positionForm" class="demo-form-inline">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="统计日期:">
                        <el-date-picker
                                v-model="positionForm.date"
                                type="date" size="small"
                                value-format="yyyy-MM-dd"
                                placeholder="开始日期">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="渠道:">
                        <el-select v-model="positionForm.channel" multiple @change="channelChange" @remove-tag="channelRemove"  size="small">
                            <el-option
                                    v-for="item in optionsChannel"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    :disabled="item.disabled">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="部门/团队/人员:">
                        <div>
                            <el-input v-model="positionForm.departmentName" :disabled="departmentDisable" size="small" icon="caret-bottom" placeholder="请选择部门"></el-input>
                            <div @click.stop="positionShowTree"
                                 style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;cursor: pointer;">
                                <div v-if="positionForm.showTree && !departmentDisable" class="department-tree-select" >
                                    <el-tree size="small"
                                             :data="departmentTree"
                                             :load="loadNode"
                                             :props="departmentTreeProps"
                                             @check-change="handleSearchCheckChange"
                                             node-key="key"
                                             ref="searchTree"
                                             show-checkbox
                                             accordion
                                             highlight-current
                                             check-strictly
                                    >
                                    </el-tree>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" class="action_col">
                    <el-form-item class="action_button_group_open">
                        <el-button size="small" type="primary" icon="el-icon-delete" @click="clearFilter">清空筛选条件</el-button>
                        <el-button size="small" type="primary" icon="el-icon-search" @click="search">查询</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row class="customer_row">
            <el-table :data="statisticsData" v-model="statisticsData" style="width: 100%;"
                      highlight-current-row
                      :summary-method="getSummaries"
                      show-summary >
                <el-table-column prop="dept" label="部门名称" align="center" min-width='95'></el-table-column>
                <!--部门为团队时显示销售员-->
                <el-table-column v-if="false" prop="seller" label="销售员" align="center" min-width='95'></el-table-column>
                <el-table-column prop="zero" label="0类" align="center" min-width='95'></el-table-column>
                <el-table-column prop="three" label="3类" align="center" min-width='95'></el-table-column>
                <el-table-column prop="eight" label="8类" align="center" min-width='95'></el-table-column>
                <el-table-column prop="sea" label="公海" align="center" min-width='95'></el-table-column>
                <el-table-column prop="class" label="客户类别统计" align="center" min-width='95'></el-table-column>
                <el-table-column prop="assignedCount" label="分配量" align="center" min-width='95'></el-table-column>
                <el-table-column prop="eightRate" label="8类占比" align="center" min-width='95'></el-table-column>

            </el-table>
        </el-row>
    </div>
</template>

<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios';
    import {Row, Col, Form, FormItem, Input, Select, Option, DatePicker, ButtonGroup,
        Button, Table, TableColumn, Message, MessageBox, Pagination, Tree
    } from 'element-ui'
    import {mapGetters, mapActions, mapMutations} from 'vuex';
    import {SHOW_MESSAGE,MESSAGE_IDS,MESSAGE_NAMES,MESSAGE_TELS} from '../../store/mutation-types/template/index';
    import {getDate , returnDate,getArraySub , getLevelName, validTel, setToken, getCookie ,uniqueArr} from '../../utils/auth'

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    Vue.use(Select);
    Vue.use(Option);

    Vue.use(DatePicker);
    Vue.use(ButtonGroup);
    Vue.use(Button);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Pagination);
    Vue.use(Tree);

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    export default {
        scrollToTop: false,
        head(){
            return {
                title: this.title
            }
        },
        data () {
            return {
                title: '转换率统计',
                tabName: '转换率统计',
                userName: '',
                teamName: '',
                filter: {
                    date:null,
                    channel: [],
                    deptId: "",
                    usId:"",
                    flag:'',
                    teamName:"",
                    userName:"",
                    moreUser:false,
                },
                departmentTree: [],
                departmentTreeProps: {
                    label: 'label',
                    children: 'children'
                },
                positionForm: {
                    date: '',
                    channel: [],
                    department: '',
                    showTree: false,
                    departmentName: ''
                },
                treeDepartment: {
                    departmentName: '',
                    showTree: false
                },
                cateShow: false,
                departmentDisable: true,
                checkedUserId:[],
                checkedUserName:[],
                statisticsData: [
                    {
                        dept: '发个梵蒂冈',
                        seller: '',
                        zero: '434',
                        three: '67',
                        eight: '534',
                        sea: '675',
                        class: '32',
                        assignedCount: '675',
                        eightRate: '12%'
                    }
                ],
                optionsChannel: [
                    {
                        value: '0',
                        label: '全部',
                        disabled: false
                    },
                    {
                        value: '1',
                        label: '百度',
                        disabled: false
                    },
                    {
                        value: '2',
                        label: '360',
                        disabled: false
                    },
                    {
                        value: '3',
                        label: '广点通',
                        disabled: false
                    },
                    {
                        value: '4',
                        label: '搜狗',
                        disabled: false
                    },
                    {
                        value: '5',
                        label: 'facebook',
                        disabled: false
                    },{
                        value: '6',
                        label: '今日头条',
                        disabled: false
                    },
                ]
            }
        },
        computed : {
            ...mapGetters({
                'pageTabsList': 'getPageTabsList',
                'userData' : 'getUserData'
            })
        },
        watch: {
            "treeDepartment.showTree"(){
                if(this.positionForm.showTree == false){
                    if(this.filter.deptId == "" && this.filter.userId == ""){
                        this.cookieUserData();
                    }
                }
            },
            cateShow(){
                this.positionForm.showTree = false;
            },
        },
        methods: {
            channelChange(val){
                if(val[val.length-1] == 0) {
                    this.positionForm.channel = ['0'];
                    for(let i=1;i<this.optionsChannel.length;i++) {
                        this.optionsChannel[i].disabled = true;
                    }
                }
            },
            channelRemove(val) {
                if(val.currentValue == 0) {
                    this.positionForm.channel = [];
                    for(let i=1;i<this.optionsChannel.length;i++) {
                        this.optionsChannel[i].disabled = false;
                    }
                }
            },
            //递归遍历Tree加入唯一key
            extendTree(data){
                let item = data;
                item.forEach((n)=>{
                    n.key = n.flag+'-'+n.id;
                    if(n.children){
                        this.extendTree(n.children)
                    }
                })
                return item;
            },
            getTreeJson(){
                if(this.departmentTree.length == 0){
                    axios.get(process.env.baseUrl + '/department/getOwnerDeptWithUser', {params:{ flag:1}})
                        .then((ret)=>{
                            let success = ret.data.successed;
                            if(success){
                                if(ret.data.data){
                                    let list = this.extendTree(ret.data.data)
                                    this.departmentTree = list;
                                    // console.log(this.departmentTree)
                                    if(!this.departmentDisable){ //如果是部门则选tree的flag
                                        this.filter.flag = this.departmentTree[0].flag;
                                    }
                                }
                            }
                        })
                }
            },

            //部门选中回调
            handleSearchCheckChange(data,checked) {
                if(checked) {
                    //如果不是同级就清空
                    if(this.filter.flag != data.flag){
                        this.$refs.searchTree.setCheckedKeys([]);
                    }
                    this.filter.flag = data.flag;
                    this.filter.level = data.level;
                    if(data.flag == 1){//1人员
                        //this.filter.usId = data.id;
                        this.filter.deptId = "";
                        this.filter.userName = data.label;
                        this.checkedUserName.push(data.label);//人员名称
                        this.checkedUserId.push(data.id);//人员id
                        this.filter.usId = this.checkedUserId.join(',');
                        this.positionForm.departmentName = this.checkedUserName.join(' / ');
                    }else{//0部门
                        this.filter.usId = "";
                        this.filter.deptId = data.id;
                        this.filter.teamName = data.label;
                        this.filter.userName = "";
                        this.$refs.searchTree.setCheckedKeys([]);//部门不支持多选

                        this.checkedUserId = [];
                        this.checkedUserName = [];

                        this.positionForm.department = data.id;
                        this.positionForm.departmentName = data.label;
                    }

                    //this.positionForm.showTree = !this.positionForm.showTree;
                    this.$refs.searchTree.setChecked(data,true)

                }else{
                    if(data.flag == 1){//1人员
                        this.checkedUserId.pop(data.id);
                        this.checkedUserName.pop(data.label);
                        this.filter.usId = this.checkedUserId.join(',');
                        this.positionForm.departmentName = this.checkedUserName.join(' / ');
                    }
                }

            },
            //获取当前用户信息
            cookieUserData(){
                let userData = getCookie('userData');
                if(userData) {
                    if(JSON.parse(userData).leaderType == "1"){//leaderType = 1则为管理者账号
                        this.departmentDisable = false;
                        this.positionForm.department = this.userData.departmentId || JSON.parse(userData).departmentId;
                        this.positionForm.departmentName = JSON.parse(userData).departmentName;
                        this.filter.teamName = this.userData.departmentName || JSON.parse(userData).departmentName;
                        this.filter.usId = "";
                        this.filter.deptId = this.userData.departmentId || JSON.parse(userData).departmentId || "";
                        this.filter.flag = "0";

                    }else{
                        this.departmentDisable = true;
                        this.positionForm.department = this.userData.id || JSON.parse(userData).id;
                        this.positionForm.departmentName = this.userData.name || JSON.parse(userData).name;
                        this.filter.usId = this.userData.id || JSON.parse(userData).id || "";
                        this.filter.level = "99";
                        this.filter.userName = this.userData.name || JSON.parse(userData).name;
                        this.filter.flag = "1";//人员
                    }
                }
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                    } else {
                        sums[index] = 'N/A';
                    }
                });

                return sums;
            },
            positionShowTree(){
                this.positionForm.showTree = !this.positionForm.showTree;
                this.positionForm.departmentName = "";
                this.positionForm.department = "";
                this.filter.usId = "";
                this.filter.deptId = "";
                this.checkedUserId = [];
                this.checkedUserName = [];
            },

            clearFilter() {
                this.positionForm.date = '';
                this.positionForm.channel = '';
                this.positionForm.department = '';
                this.positionForm.departmentName = '';

                this.filter.deptId = '';
                this.filter.usId = '';
                this.filter.flag = '';
                this.filter.teamName = '';
                this.filter.userName = '';
                this.filter.moreUser = false;
                for(let i=1;i<this.optionsChannel.length;i++) {
                    this.optionsChannel[i].disabled = false;
                }
            },
            search() {

            }

        },
        created(){
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        },

        mounted(){
            this.cookieUserData();
            this.getTreeJson();
        }
    }

</script>

<style scoped lang="scss">
    html,body{
        height: 100%;
    }
    .customer-box{

    }
    .department-tree-select{
        width: 130%;
        max-height: 400px;
        overflow: auto;
    }



</style>